#include "node.h"
#include <iostream>

using namespace std;

pthread_mutex_t Node::lock;

Node::Node(string name, string IP, list<string*> *console) {
	output = console;
	pthread_mutex_init(&lock, NULL);
	active = false;
	online = false;
	verbose = false;
	hostname = name;
	hostip = IP;
};

string Node::getHostname() {return hostname;};

string Node::getIP() {return hostip;};

void Node::execute(string *cmd) {
	string *edited = new string(*cmd);
	string *final = NULL;
	string *result = NULL;
	boost::replace_all(*edited,"$host",hostname);
	boost::replace_all(*edited,"$ip",hostip);
	if(verbose) {
		pthread_mutex_lock(&lock);
		final = new string(hostname + ": " + *edited + "\n");
		if(output != NULL) {output->push_back(final);}
		else {cout << *final << endl;}
		pthread_mutex_unlock(&lock);
	} int status;
	char line[255];
	FILE *fp = popen(edited->c_str(),"r");
	if (fp != NULL) {
		while (fgets(line, 255, fp) != NULL) {
			pthread_mutex_lock(&lock);
			result = new string(hostname + ": " + line);
			if(output != NULL) {output->push_back(result);}
			else {cout << *result;}
			pthread_mutex_unlock(&lock);
		}
	} status = pclose(fp);
};

void Node::setOnline(bool on) {online = on;};

bool Node::isOnline() {return online;};

void Node::setActive(bool act) {active = act;};

bool Node::isActive() {return active;};

string Node::toString() {
	return hostname + " (" + hostip + ") " + (online? "online" : "offline") + " and " + (active? "active" : "inactive");
};

